import { login } from "../../apis/login"
// import { request } from "@/utils/request";
import { createSlice } from "@reduxjs/toolkit";
import { setToken as setTokenUtil, getToken, removeToken as removeTokenUtil } from "@/utils/token";
import { getUserInfo } from "../../apis/user";
const userStore = createSlice({
    name: "user",
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    reducers: {
        setToken: (state, action) => {
            state.token = action.payload
            // localStorage.setItem('token', action.payload)
            // setTokenUtil(action.payload)
        },
        removeToken: (state) => {
            state.token = ''
            state.userInfo = {}
            removeTokenUtil()
        },
        setUserInfo: (state, action) => {
            state.userInfo = action.payload
        }
    }
})
const { setToken, setUserInfo, removeToken } = userStore.actions
// 异步登录 获取token
const loginAction = (params) => {
    return async dispatch => {
        const res = await login(params)
        // const res = await request.post('/authorizations', params)
        console.log(res);
        if (res.data.data.token) {
            // 登录成功
            // 1.保存token
            dispatch(setToken(res.data.data.token))
            setTokenUtil(res.data.data.token)
        }
    }
}
// 异步获取用户信息
const getUserInfoAction = () => {
    return async dispatch => {
        const res = await getUserInfo()
        dispatch(setUserInfo(res.data.data))
    }
}
export { setToken, loginAction, getUserInfoAction, setUserInfo, removeToken }
const reducer = userStore.reducer
export default reducer